﻿using System.ComponentModel.DataAnnotations;

namespace RotaractProjectCalendar.Models
{
    public class MaxWordsAttribute : ValidationAttribute
    {
        public MaxWordsAttribute(int maxWords) : base("{0} has too many words.")
        {
            _maxWords = maxWords;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return ValidationResult.Success;
            }
            var valueAsString = value.ToString();
            if (valueAsString.Split(' ').Length <= _maxWords)
            {
                return ValidationResult.Success;
            }
            var errorMessage = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(errorMessage);
        }

        private readonly int _maxWords;
    }
}